import { Extension } from '@tiptap/core'
import { Plugin, PluginKey } from 'prosemirror-state'
import { nanoid } from "nanoid";
export const pasteRules = (getEdit) => Extension.create({
    name: 'pasteRules',
    addProseMirrorPlugins() {
        return [
            new Plugin({
                key: new PluginKey('pasteRules'),
                props: {
                    handlePaste(view, event) {
                        // 获取剪贴板内容
                        const clipboardData = event.clipboardData || window.clipboardData;
                        const pastedText = clipboardData.getData('text/plain'); // 获取纯文本
                        const pastedHTML = clipboardData.getData('text/html'); // 获取HTML内容
                        // 示例：将粘贴的HTML转换为Tiptap的JSON格式
                        // const parser = new DOMParser();
                        // const doc = parser.parseFromString(pastedHTML, 'text/html');
                        // const tiptapJSON = editor.schema.nodes.doc.create(doc.body.childNodes);
                        const { state, dispatch } = view;
                        const { selection, tr } = state;
                        const { from, to, $from, $to } = selection;
                        const editor = getEdit();
                        

                        const size = state.doc.content.size
                        const entireDocSelected = to <= size;
                        // 如果全选了当前内容 则删除其余小圆点 并插入新的小圆点和内容
                        if (entireDocSelected && (from <= 1) && !selection.empty) {
                            const id = nanoid();
                            event.preventDefault();
                            editor
                                .chain()
                                .deleteSelection()
                                .setContent(`<speak subId="${id}">${pastedText}</speak>`)
                                .focus()
                                .run()
                            return true


                            editor.commands.clearContent()
                            editor.commands.clearContent()
                            editor.commands.setContent(`<speak subId="${id}">${pastedText}</speak>`)
                            editor.commands.focus(1)
                            return true             
                                // editor.commands.deleteRange({ from, to })
                                // editor.commands.deleteSelection()
                                // editor.commands.setContent(`<speak subId="${id}"><p>${pastedText}</p></speak>`)
                        }

                        event.preventDefault();
                        editor
                            .chain()
                            .deleteSelection()
                            .insertContentAt(from, pastedText)
                            .focus()
                            .run()
                        return true

                    },
                },
            })
        ]
    }
});
